package com.getsendsocial.GetSendSocial.Database;

import java.util.ArrayList;


import com.getsendsocial.GetSendSocial.R;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

public class ContactAdapter extends ArrayAdapter<String> implements Filterable {

	private ArrayList<String> objects;
    private ModelFilter filter;
    private ArrayList<String> filteredModelItemsArray;
    private Context ctx;
    private ContentResolver cr;
	

	public ContactAdapter(Context context, int textViewResourceId, ArrayList<String> objects, ContentResolver content) {
		super(context, textViewResourceId, objects);
		this.objects = objects;
		this.ctx=context;
		this.cr = content;
	}

	/*
	 * we are overriding the getView method here - this is what defines how each
	 * list item will look.
	 */
	public View getView(int position, View convertView, ViewGroup parent){

		// assign the view we are converting to a local variable
		View v = convertView;

		// first check to see if the view is null. if so, we have to inflate it.
		// to inflate it basically means to render, or show, the view.
		if (v == null) {
			LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.list_item, null);
		}

		/*
		 * Recall that the variable position is sent in as an argument to this method.
		 * The variable simply refers to the position of the current object in the list. (The ArrayAdapter
		 * iterates through the list we sent it)
		 * 
		 * Therefore, i refers to the current Item object.
		 */
		String i = objects.get(position);
		
		TextView tt = (TextView) v.findViewById(R.id.name);

		if (i != null) {

			// This is how you obtain a reference to the TextViews.
			// These TextViews are created in the XML files we defined.

			if (tt != null){
				
				tt.setText(i);
			}
			
		}

		// the view must be returned to our activity
		return v;
		
		
	}
	
	@Override
    public Filter getFilter() {
        if (filter == null){
          filter  = new ModelFilter();
        }
        return filter;
      }
	
	private class ModelFilter extends Filter
    {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            
            constraint = constraint.toString().toLowerCase();
            FilterResults result = new FilterResults();
            if(constraint != null && constraint.toString().length() > 0){
                ArrayList<String> filteredItems = new ArrayList<String>();
                if(!objects.isEmpty()){
                	objects.clear();
                }
                ArrayList<String> temp = new ArrayList<String>();				
				Cursor contactCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{Phone.DISPLAY_NAME}, Phone.DISPLAY_NAME + " like ?",new String[]{constraint+ "%"}, Phone.DISPLAY_NAME + " ASC");
				while(contactCursor.moveToNext()){
					String name = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					if (!temp.contains(name)){
						objects.add(name);
						temp.add(name);
					}
					
					
				}
				contactCursor.close();
				temp.clear();
				for(int i = 0, l = objects.size(); i < l; i++)
                {
                    String m = objects.get(i);
                    if(m.toLowerCase().contains(constraint))
                        filteredItems.add(m);
                }
                result.count = filteredItems.size();
                result.values = filteredItems;
            }else{
                synchronized(this)
                {
                	ArrayList<String> list = new ArrayList<String>();
	                ArrayList<String> temp = new ArrayList<String>();
	                list.add("Inserisci Numero");
    				Cursor contactCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{Phone.DISPLAY_NAME}, null,null, Phone.DISPLAY_NAME + " ASC");
    				while (contactCursor.moveToNext()){
    	                String name = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    					if (!temp.contains(name)){
    						list.add(name);
    						temp.add(name);
    					}
    				}
                    result.values = list;
                    result.count = list.size();
                    
                }
            }
            return result;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
           
            filteredModelItemsArray = (ArrayList<String>)results.values;
            notifyDataSetChanged();
            clear();
            for(int i = 0, l = filteredModelItemsArray.size(); i < l; i++)
                add(filteredModelItemsArray.get(i));
            notifyDataSetInvalidated();
        }
   }
}
          

